package com.qianbei.view.transport;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.qianbei.R;
import com.qianbei.bean.ChangeStationBean;
import com.qianbei.bean.GetBoxBody;
import com.qianbei.bean.GetBoxBody1;
import com.qianbei.bean.GetEmpty_Body;
import com.qianbei.bean.GetNamebean;
import com.qianbei.bean.GetRecord;
import com.qianbei.bean.GetTransportStart;
import com.qianbei.bean.GetUpbox;
import com.qianbei.bean.RequeastBean1;
import com.qianbei.bean.SkipBean;
import com.qianbei.bean.SkipReasonType;
import com.qianbei.bean.SkipReasonTypeBean;
import com.qianbei.common.base.ActivityManagers;
import com.qianbei.common.base.BaseActivity;
import com.qianbei.common.base.Basebean;
import com.qianbei.common.base.MyApplication;
import com.qianbei.common.init.SetData;
import com.qianbei.common.net.control.ServerControl;
import com.qianbei.common.net.control.ServerResult;
import com.qianbei.common.net.okhttp.RequeastBean;
import com.qianbei.common.net.view.MsgAlert;
import com.qianbei.common.net.view.ProgressDialog;
import com.qianbei.common.net.view.ToastAlert;
import com.qianbei.common.util.DeviceUtil;
import com.qianbei.view.EpcDataBase;
import com.qianbei.view.bluetooth.BluetoothService;
import com.qianbei.view.bluetooth.Const;
import com.qianbei.view.bluetooth.DeviceScanActivity;
import com.qianbei.view.bluetooth.LoadDataResp;
import com.qianbei.view.orm.DaoSession;
import com.qianbei.view.orm.RFID;
import com.qianbei.view.orm.RFIDDao;
import com.qianbei.view.orm.RequestPersistent;

import org.greenrobot.greendao.query.Query;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RecordweightActivity extends BaseActivity {
    private static final String TAG = RecordweightActivity.class.getSimpleName();
    TextView ts_company;
    TextView ts_address;
    TextView contactPerson;
    TextView contactPhone;
    TextView empty_big_box;
    TextView empty_small_box;
    TextView full_small_box;
    TextView full_big_box;
    TextView tvSkip;
    TrasportBean.ArrayBean.CustomerAryBean c;
    private RFIDDao rfidDao;
    private SharedPreferences pref;
    private Boolean flag;
    private List<SkipReasonType> reasonTypes;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.gufei_record_weight_activity);
        setTitle("收运情况");
        Bundle b = getIntent().getExtras();
        c = (TrasportBean.ArrayBean.CustomerAryBean) b.get("key");
        changeStatus(c.getId());
        ts_company = (TextView) findViewById(R.id.ts_company);
        ts_address = (TextView) findViewById(R.id.ts_address);
        contactPerson = (TextView) findViewById(R.id.contactPerson);
        contactPhone = (TextView) findViewById(R.id.contactPhone);
        empty_big_box = (TextView) findViewById(R.id.empty_big_box);
        empty_small_box = (TextView) findViewById(R.id.empty_small_count);
        full_small_box = (TextView) findViewById(R.id.full_small_box);
        full_big_box = (TextView) findViewById(R.id.full_big_box);
        tvSkip = (TextView) findViewById(R.id.tv_skip);
        mTitle.setRightImage(R.drawable.ic_bluetooth);
        ts_company.setText(c.getCustomerName());
        ts_address.setText(c.getAddress());
        contactPerson.setText(c.getContactPerson());
        contactPhone.setText(c.getContactPhone());
        findViewById(R.id.empty_box).setOnClickListener(this);
        findViewById(R.id.empty_box2).setOnClickListener(this);
        findViewById(R.id.shou_ok).setOnClickListener(this);
//        findViewById(R.id.title_right).setVisibility(View.GONE);
        tvSkip.setOnClickListener(this);
        //存储空箱扫描是否被保存过的标记 。需求来源：目前的界面是【空箱装卸】和【重箱装卸】是并列显示的，希望修改成先显示【空箱装卸】完成空箱任务后再出现【重箱装卸】。
        pref = getSharedPreferences("isOver", 0);
        flag = pref.getBoolean("id" + c.getId(), false);
        if (!flag) {
            //没有扫描并保存 过空箱子，需要把重箱隐藏起来
            findViewById(R.id.full_area).setVisibility(View.GONE);
        }
        if (SetData.getBusinessType() == 3) {//BusinessType 3 固废  不需要扫箱子
            findViewById(R.id.empty_area).setVisibility(View.GONE);
            findViewById(R.id.full_area).setVisibility(View.GONE);
        }

        DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
        rfidDao = daoSession.getRFIDDao();
//       if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存)
        initBluetooth();
//       }
    }

    @Override
    public void fClick(int id) {
        super.fClick(id);
        switch (id) {
            case R.id.title_right:
                startActivity(DeviceScanActivity.class);
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!TextUtils.isEmpty(SetData.getJobid()) && c != null && !TextUtils.isEmpty(c.getId())) {
            QueryBuilder<RFID> qb = rfidDao.queryBuilder();
            qb.where(qb.and(RFIDDao.Properties.JobId.eq(SetData.getJobid()), RFIDDao.Properties.WhichStep.eq("BoxLoadAndUnload"),
                    RFIDDao.Properties.CustomerId.eq(c.getId()), RFIDDao.Properties.Empty.eq(true)));
            qb.orderAsc(RFIDDao.Properties.BoxTypeIntVal);

            Query<RFID> query = qb.build();

            int emptyBig = 0, emptySmall = 0;
            int fullBig = 0, fullSmall = 0;
            List<RFID> emptyRes = qb.list();

            for (RFID rfid : emptyRes) {
                if (rfid.getBoxTypeIntVal() != 0) {
                    int val = rfid.getBoxTypeIntVal();
                    if (val == 1 || val == 3) {
                        emptySmall++;
                    } else if (val == 2 || val == 4) {
                        emptyBig++;
                    }
                }
            }


            query.setParameter(3, false);
            List<RFID> fullRes = query.list();

            for (RFID rfid : fullRes) {
                if (rfid.getBoxTypeIntVal() != 0) {
                    int val = rfid.getBoxTypeIntVal();
                    if (val == 1 || val == 3) {
                        fullSmall++;
                    } else if (val == 2 || val == 4) {
                        fullBig++;
                    }
                }
            }
            empty_big_box.setText("X " + emptyBig);
            empty_small_box.setText("X " + emptySmall);
            full_big_box.setText("X " + fullBig);
            full_small_box.setText("X " + fullSmall);
        }
    }

    /**
     * 查询初始载重
     */
    private void initBluetooth() {
        if (BluetoothService.getInstance().getState() != BluetoothService.STATE_CONNECTED) {
            new MsgAlert().show("请连接蓝牙设备");
            startActivity(DeviceScanActivity.class);
        }
    }

    private void queryLoad(final int sendId) {
        if (BluetoothService.getInstance().getState() != BluetoothService.STATE_CONNECTED) {
            return;
        }
        BluetoothService.getInstance().queryLoadData(sendId);
        BluetoothService.getInstance().setOnDataListener(new BluetoothService.OnDataListener() {
            @Override
            public void onFetchLoadData(String loadData) {
                Log.i(TAG, loadData);
                try {
                    LoadDataResp dataResp = new Gson().fromJson(loadData, LoadDataResp.class);
                    if (Const.SENDID_NULLBOX == sendId) {
                        SetData.setNullBoxWeight(dataResp.getGR_LoadRsp().getLoadOutput());
                    } else if (Const.SENDID_FULLBOX == sendId) {
                        SetData.setFullBoxWeight(dataResp.getGR_LoadRsp().getLoadOutput());
                    }
                } catch (Exception e) {
                    Log.w(TAG, "载重数据解析出错");
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoadDataFail() {
                if (BluetoothService.getInstance().getState() == BluetoothService.STATE_CONNECTED) {
                    BluetoothService.getInstance().queryLoadData(sendId);
                } else {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            new MsgAlert().show("蓝牙连接已经断开");
                        }
                    });
                }
            }
        });
    }
    private boolean isFirst=true;
    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.empty_box:
                if (isFirst && BluetoothService.getInstance().getState() != BluetoothService.STATE_CONNECTED) {
                    isFirst = false;
                    new MsgAlert().show("蓝牙未连接");
                  /*  startActivity(DeviceScanActivity.class);
                    return;*/
                }
                /*int nullBoxWeight = SetData.getNullBoxWeight();
                if (nullBoxWeight < 0) {
                    queryLoad(Const.SENDID_NULLBOX);
                }*/
                Intent i = new Intent(mContext, EmptyUPActivity.class);
                i.putExtra("id", c.getId());
                i.putExtra("box", "empty");

                startActivityForResult(i, 2);


                break;
            case R.id.empty_box2:
                Intent i1 = new Intent(mContext, EmptyUPActivity.class);
                i1.putExtra("id", c.getId());
                i1.putExtra("box", "full");
                startActivityForResult(i1, 1);

                break;
            case R.id.shou_ok:

           /*     if (!full_big_box.getText().toString().equals("X 0") ||
                        !full_small_box.getText().toString().equals("X 0")
                        || SetData.getBusinessType() == 3) { //BusinessType 3 固废  没有周转箱*/
                if (SetData.getBusinessType() != 3) { //BusinessType 3 固废  没有周转箱 bug007=>没有重箱也能操作下一步
                    Intent is = new Intent(mContext, RecordweightActivity2.class);
                    Bundle mBundle = new Bundle();
                    mBundle.putSerializable("key", c);
                    if (!full_big_box.getText().equals("")) {
                        mBundle.putString("full_big_box",full_big_box.getText().toString().substring(2,full_big_box.length()) );
                    }
                    if (!empty_big_box.getText().equals("")) {
                        mBundle.putString("empty_big_box",empty_big_box.getText().toString().substring(2,empty_big_box.length()) );
                    }
                    if (!full_small_box.getText().equals("")) {
                        mBundle.putString("full_small_box",full_small_box.getText().toString().substring(2,full_small_box.length()) );
                    }
                    if (!empty_small_box.getText().equals("")) {
                        mBundle.putString("empty_small_box",empty_small_box.getText().toString().substring(2,empty_small_box.length()) );
                    }
                    is.putExtras(mBundle);
                    startActivity(is);
                } else {
                    new MsgAlert().show("请进行重箱装卸扫描");
                }
                break;
            case R.id.tv_skip:
                loadReasonTypes();
                break;
        }
    }

    /**
     * 跳过这个工单
     */
    private void loadReasonTypes() {
        if (reasonTypes != null && reasonTypes.size() != 0) {
            showReasonDialog(reasonTypes);
        } else {
            SkipReasonTypeBean typeBean = new SkipReasonTypeBean();
            SkipReasonTypeBean.TypesBean bean = new SkipReasonTypeBean.TypesBean();
            bean.setType("skipReasonTypes");
            List<SkipReasonTypeBean.TypesBean> typesBeans = new ArrayList<>();
            typesBeans.add(bean);
            typeBean.setTypes(typesBeans);
            RequeastBean requeastBean =
                    new RequeastBean("getDictList", "com.cygps.dubbo.WasteTransport.IDictDetail",
                            typeBean);
            ServerControl sc = new ServerControl(requeastBean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        try {
                            org.json.JSONObject jsonObject = sr.bodyData.optJSONObject("array");
                            org.json.JSONArray types = jsonObject.optJSONArray("skipReasonTypes");
                            reasonTypes = JSON.parseArray(types.toString(), SkipReasonType.class);
                            if (reasonTypes != null && reasonTypes.size() != 0) {
                                Collections.reverse(reasonTypes);
                                showReasonDialog(reasonTypes);
                            } else {
                                new MsgAlert().show("加载跳过的原因选项出错");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            };
            new ProgressDialog(mContext).OKpost(sc,"正在加载...");
        }
    }
    private int index;
    private void showReasonDialog(List<SkipReasonType> reasonTypes) {
        int size = reasonTypes.size();
        final String[] reasons = new String[size];
        for (int i = 0; i < size; i++) {
            SkipReasonType type = reasonTypes.get(i);
            reasons[i] = type.getName();
        }
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("请选择跳过的原因")//设置对话框的标题
                .setSingleChoiceItems(reasons, 0, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        index = which;
                    }
                })
                //设置对话框的按钮
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        saveOrder(reasons[index]);
                        dialog.dismiss();
                    }
                }).create();
        dialog.show();
    }
   /* *//**
     * 保存工单
     *//*
    private void saveOrder(String reason) {
        ArrayList<String> photo_ids = new ArrayList<>();
        photo_ids.add("photo is null");
        ArrayList<String> photo_names = new ArrayList<>();
        photo_names.add(reason);
        changeCacheStatus(c.getId(),true);
        RequeastBean bean =
                new RequeastBean("sign", "com.cygps.dubbo.WasteTransport.IRouteInfo",
                        new GetNamebean(c.getId(), photo_ids,photo_names));
        if (!DeviceUtil.isNetworkAvailable()) {
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetNamebean.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            new MsgAlert().show("已跳过该收运点");
            finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("已跳过该收运点");
                        finish();
                    }
                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }*/
    private void saveOrder(String reason) {
        changeCacheStatus(c.getId(),true);
        RequeastBean bean =
                new RequeastBean("skip", "com.cygps.dubbo.WasteTransport.IInputKg",
                        new SkipBean(SetData.getJobid(),c.getId(),reason));
        if (!DeviceUtil.isNetworkAvailable()) {
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(SkipBean.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            new MsgAlert().show("已跳过该收运点");
            finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {
                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {
                        new MsgAlert().show("已跳过该收运点");
                        finish();
                    }
                }
            };
            new ProgressDialog(mContext).OKpost(sc);
        }
    }


    // 回调方法，从第二个页面回来的时候会执行这个方法
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {


        flag = pref.getBoolean("id" + c.getId(), false);
        if (flag) {
            //空箱子执行过保存方法，需要把重箱显示
            findViewById(R.id.full_area).setVisibility(View.VISIBLE);
        }
        Log.d("gaoaa", "" + resultCode + ",,,requestCode:" + requestCode + ",,,flag:" + flag);

        if (resultCode == 0 && data != null) {
            String big = data.getStringExtra("big");
            String small = data.getStringExtra("small");
            // 根据上面发送过去的请求吗来区别
            switch (requestCode) {
                case 1:
                    queryLoad(Const.SENDID_FULLBOX);
                    full_big_box.setText("X " + big);
                    full_small_box.setText("X " + small);
                    try {
                        int bigNum = Integer.parseInt(big);
                        int smallNum = Integer.parseInt(small);
                        float weight = bigNum * Const.BIG_BOX_WEIGHT + smallNum * Const.SMALL_BOX_WEIGHT;
                        SetData.setBoxInstallWeight(weight);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    break;
                case 2:
                    queryLoad(Const.SENDID_NULLBOX);
                    empty_big_box.setText("X " + big);
                    empty_small_box.setText("X " + small);
                    //大箱小箱
                    try {
                        int bigNum = Integer.parseInt(big);
                        int smallNum = Integer.parseInt(small);
                        float weight = bigNum * Const.BIG_BOX_WEIGHT + smallNum * Const.SMALL_BOX_WEIGHT;
                        SetData.setBoxUnInstallWeight(weight);
                    } catch (NumberFormatException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    break;
            }
        }

    }

    /**
     * 改变收运状态
     *
     * @param customerId
     */
    private void changeStatus(String customerId) {
        Log.d("ChangeJobCusStatus", customerId);
        RequeastBean bean = new RequeastBean("changeStatus", "com.cygps.dubbo.WasteTransport.ICustomersplit",
                new GetTransportStart(customerId));

        changeCacheStatus(customerId,false);

        if (!DeviceUtil.isNetworkAvailable()) {//没用网络 缓存数据到内存
//            MyApplication.netList.add(bean);//bug001
            DaoSession daoSession = ((MyApplication) getApplication()).getDaoSession();
            RequestPersistent requestPersistent = new RequestPersistent();
            requestPersistent.setServiceName(bean.serviceName);
            requestPersistent.setServiceMethod(bean.serviceMethod);
            requestPersistent.setServiceBody(new Gson().toJson(bean.serviceBody));
            requestPersistent.setMethodClass(GetTransportStart.class.getName());
            daoSession.getRequestPersistentDao().insertOrReplace(requestPersistent);
            //new MsgAlert().show("现在没用网络，数据已保存 有网络的时候会自动提交");
            //finish();
        } else {
            ServerControl sc = new ServerControl(bean);
            sc.serverListener = new ServerControl.ServerListener() {

                @Override
                public void serverFinish(ServerResult sr) {
                    if (sr.isContinue) {

                    }

                }
            };
            sc.OKpost();
        }
    }

    /**
     * 更新缓存中指定客户的收运状态
     *
     * @param customerId
     */
    private void changeCacheStatus(String customerId,boolean isSkip) {
        String jsonString = SetData.getJobs();
        JSONArray jobsAry = JSON.parseArray(jsonString);
        String jobId = SetData.getJobid();

        for (int i = 0; i < jobsAry.size(); i++) {
            JSONObject oneJob = jobsAry.getJSONObject(i);
            String dataJobId = oneJob.getString("_id");
            if (dataJobId.equals(jobId)) {
                JSONArray cusAry = oneJob.getJSONArray("customerAry");
                for (int j = 0; j < cusAry.size(); j++) {
                    JSONObject oneCus = cusAry.getJSONObject(j);
                    String cusId = oneCus.getString("id");
                    if (cusId.equals(customerId)) {
                        String oldStatus = oneCus.getString("status");
                        if (isSkip) {
                            if (oldStatus.equals("1")) {
                                oneCus.put("status", "2");//1 完成收运
                                SetData.setJobs(jobsAry.toJSONString());
                            }
                        } else {
                            if (oldStatus.equals("0")) {
                                oneCus.put("status", "1");//1 收运中
                                SetData.setJobs(jobsAry.toJSONString());
                            }
                        }
                        break;
                    }
                }
                break;
            }
        }
    }
}
